package com.example.a10928.weifriend.ui.task_center

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.Intent
import android.databinding.Observable
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.databinding.ViewDataBinding
import android.graphics.Color
import android.view.View
import com.example.a10928.weifriend.App.app
import com.example.a10928.weifriend.R
import com.example.a10928.weifriend.binding.SimpleOnPropertyChangedCallback
import com.example.a10928.weifriend.ui.DatabindingBaseActivity
import com.example.a10928.weifriend.util.L
import com.example.a10928.weifriend.util.RxUtil
import com.mylhyl.circledialog.CircleDialog
import android.content.ClipboardManager
import android.content.Context
import android.text.TextUtils
import android.widget.ImageView
import com.example.a10928.weifriend.App.activity
import com.example.a10928.weifriend.databinding.ActivityTaskDetailsBinding
import com.example.a10928.weifriend.http.api.VariableName
import com.example.a10928.weifriend.http.api.base.ImageViewInfo
import com.example.a10928.weifriend.http.configuration.ApiException
import com.example.a10928.weifriend.ui.home.menu.UpdateVIPActivity
import com.jaeger.ninegridimageview.ItemImageClickListener
import com.jaeger.ninegridimageview.NineGridImageViewAdapter
import com.previewlibrary.GPreviewBuilder
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_qr.view.*
import java.util.logging.Handler


class TaskDetailsActivity : DatabindingBaseActivity() {
    var taskType: Int = -1
    var adId: Int? = -1
    var data: String = ""
    var isFinish: ObservableBoolean = ObservableBoolean(true)
    var isImageShow: ObservableBoolean = ObservableBoolean(true)

    var mData: ObservableField<DetailsData> = ObservableField()
    var isShow: ObservableBoolean = ObservableBoolean(false)
    lateinit var mBinding: ActivityTaskDetailsBinding

    override fun bindingInitData() {
        val type = intent.getIntExtra(SOURCE_TASKDETAILS_TYPE, -1)
        when (type) {
            SOURCE_TAKE_TEH_TASK -> {
                setTitleText(ThemeEnum.Back_Default, "广告详情")
                isShow.set(false)
                adId = getIntent().getIntExtra(DATA_TAKE_THE_TASK, -1)
                taskType = SOURCE_TAKE_TEH_TASK
            }
            SOURCE_SEND_THE_TASK -> {
                setTitleText(ThemeEnum.Back_Default, "任务详情")
                isShow.set(true)
                adId = getIntent().getIntExtra(DATA_TAKE_THE_TASK, -1)
                taskType = SOURCE_SEND_THE_TASK
            }
            else -> {
                return
            }
        }
    }

    override fun bindingInitView(viewDataBinding: ViewDataBinding?) {
        mBinding = viewDataBinding as ActivityTaskDetailsBinding
        mBinding.setView(this)
        when (taskType) {
            SOURCE_TAKE_TEH_TASK -> {
                getAdverDetail()
            }
            SOURCE_SEND_THE_TASK -> {
                getTaskDetail()
                mBinding.detailsGet.setText("立即提交")
            }
            else -> {
                return
            }
        }

        mData.addOnPropertyChangedCallback(object : SimpleOnPropertyChangedCallback() {
            override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
                var imags :MutableList<ImageViewInfo> = mutableListOf()
                for (urls in mData.get()!!.imgs){
                    imags.add(ImageViewInfo(urls))
                }

                mBinding.detailsNglImages.setAdapter(object : NineGridImageViewAdapter<ImageViewInfo>() {
                    override fun onDisplayImage(context: Context?, imageView: ImageView?, t: ImageViewInfo) {
                        Picasso.with(context).load(t!!.url).error(R.drawable.ic_default_image)
                                .placeholder(R.drawable.ic_default_image).into(imageView)
                    }
                })
                mBinding.detailsNglImages.setItemImageClickListener( object :ItemImageClickListener<ImageViewInfo>{
                    override fun onItemImageClick(context: Context?, imageView: ImageView?, index: Int, list: MutableList<ImageViewInfo>?) {
                        GPreviewBuilder.from(activity)
                                .setData(list!!)
                                .setCurrentIndex(index)
                                .setUserFragment(ImageShowFragment::class.java)
                                .setType(GPreviewBuilder.IndicatorType.Dot)
                                .start()//启动
                    }
                })

                mBinding.detailsNglImages.setImagesData(imags)
                if(imags.size == 1){
                    mBinding.detailsImage.visibility = View.VISIBLE
                    mBinding.detailsNglImages.visibility = View.INVISIBLE
                    Picasso.with(activity).load(imags[0].url).error(R.drawable.ic_default_image)
                            .placeholder(R.drawable.ic_default_image).into(mBinding.detailsImage)
                    mBinding.detailsImage.setOnClickListener{
                        GPreviewBuilder.from(activity)
                                .setSingleData(ImageViewInfo(imags[0].url))
                                .setCurrentIndex(0)
                                .setUserFragment(ImageShowFragment::class.java)
                                .setType(GPreviewBuilder.IndicatorType.Dot)
                                .start()//启动
                    }
                }
            }
        })
    }


    override fun bindingGetContentView(): Int {
        return R.layout.activity_task_details
    }

    public fun onViewClick(v: View) {
        when (v.id) {
            R.id.details_get -> {
                when (taskType) {
                    SOURCE_TAKE_TEH_TASK -> {
                        getTask()
                    }
                    SOURCE_SEND_THE_TASK -> {
                        var intent = Intent(this, SubmitTaskActivity::class.java)
                        intent.putExtra(SubmitTaskActivity.DATA_ADVER_ID, adId);
                        intent.putExtra(VariableName.DATA, data)
                        startActivity(intent)
                    }
                    else -> {
                        return
                    }
                }

            }
            R.id.details_copy_text -> {
                if (!TextUtils.isEmpty(mBinding.detailsTextInfo.getText().toString())) {
                    val myClipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                    val myClip: ClipData
                    myClip = ClipData.newPlainText("code", mBinding.detailsTextInfo.getText().toString())
                    myClipboard!!.setPrimaryClip(myClip)
                    L.t("复制成功")
                }
            }
        }
    }

    fun getTaskDetail() {
        app().bpService.getTaskDetail(app().user.userId, adId!!)
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        { r ->
                            if (r.data.is_finish != 0) {
                                isFinish.set(false)
                            }
                            if(r.data.adver_img_url.size == 1){
                                isImageShow.set(false)
                            }
                            mData.set(DetailsData(
                                    r.data.ad_title,
                                    r.data.ad_content,
                                    r.data.adver_img_url,
                                    r.data.commission,
                                    r.data.created_at))
                        },
                        { RxUtil::errorException }
                );
    }

    @SuppressLint("CheckResult")
    fun getAdverDetail() {
        app().bpService.getAdverDetail(app().user.userId, adId!!)
                .compose(RxUtil.io2mainLoad(this))
                .subscribe(
                        { r ->
                            if(r.data.adver_img_url.size == 1){
                                isImageShow.set(false)
                            }
                            mData.set(DetailsData(
                                    r.data.ad_title,
                                    r.data.ad_content,
                                    r.data.adver_img_url,
                                    r.data.ad_unit_price,
                                    r.data.created_at))

                        }, { RxUtil::errorException }
                )
    }

    fun getTask() {
        CircleDialog.Builder()
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setTitle("任务领取")
                .setText("确认领取任务")
                .setNegative("取消", null)
                .setPositive("确定") { v ->

                    app().bpService.getAdver(app().user.userId, adId!!)
                            .compose(RxUtil.io2mainLoad(this))
                            .subscribe(
                                    { r ->
                                        L.tLong("任务领取成功")
                                        android.os.Handler().postDelayed(Runnable {
                                            this.finish()

                                        },500)
                                    }, { e ->
                                if (e is ApiException) {
                                    if (e.code == 4009) {
                                        startActivity(Intent(activity, UpdateVIPActivity::class.java))
                                    }

                                    if ((e as ApiException).code == 4001) {
                                        L.t((e as ApiException).msg)
                                    } else {
                                        RxUtil.errorException(e)
                                    }

                                }
                            }
                            )

                }
                .configNegative { params -> params.textColor = Color.RED }
                .show(this.getSupportFragmentManager())

    }

    class DetailsData(title: String, content: String, imgs: List<String>, price: String, date: String) {
        public var title = title
        public var content = content
        public var imgs = imgs
        public var price = price
        public var date = date

        constructor(title: String, content: String, imgs: List<String>)
                : this(title, content, imgs, "", "")

    }

    companion object {
        val SOURCE_TASKDETAILS_TYPE: String = "sourceTaskDetailsActivityType"
        val DATA_TAKE_THE_TASK: String = "data_ad_id"
        val SOURCE_TAKE_TEH_TASK = 1005
        val SOURCE_SEND_THE_TASK = 1006
    }

}